package de.godlike.webgui;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;

import de.godlike.services.DiskInfo;
import de.godlike.services.File;
import de.godlike.webgui.internal.BeanManager;

@ManagedBean
@ViewScoped
public class FileBrowserBean {
	private final JWebminBean sessionBean = BeanManager.findBean("jWebminBean",
			JWebminBean.class);
	private final SystemInfoBean sysInfoBean = BeanManager.findBean(
			"systemInfoBean", SystemInfoBean.class);
	private final List<File> fileList = new ArrayList<File>();
	private final List<DiskInfo> diskList;
	private String lastPath;
	private String currentPath;

	public FileBrowserBean() {
		this.diskList = this.sysInfoBean.getDiskList();
	}

	/**
	 * @return the fileList
	 */
	public List<File> getFileList() {
		return this.fileList;
	}

	private boolean folderIsMountpoint(String folder) {
		if (this.diskList != null) {
			for (DiskInfo mountpoint : this.diskList) {
				if (mountpoint.getMountPoint().equals(folder)) {
					return true;
				}
			}
		}
		return false;
	}

	public void retrieveFileList(ActionEvent event) {
		String folder = (String) event.getComponent().getAttributes()
				.get("folder");
		if (folder != null) {
			this.fileList.clear();

			if (folder.equals("..")) {
				String tmp = this.currentPath;
				this.currentPath = this.lastPath;
				this.lastPath = tmp;
			} else {
				if (this.folderIsMountpoint(folder)) {
					this.currentPath = folder;
				} else {
					this.lastPath = this.currentPath;
					this.currentPath += "/" + folder;
				}
			}

			if (!this.folderIsMountpoint(this.currentPath)) {
				File backFile = new File();
				backFile.setName("..");
				backFile.setDirectory(true);
				backFile.setFile(false);
				this.fileList.add(backFile);
			}

			this.fileList.addAll(this.sessionBean.getService().listDir(
					this.currentPath));
		}
	}
}
